package com.wlj.web.controller;

import com.fasterxml.jackson.annotation.JsonView;
import com.wlj.security.core.properties.WljSecurityProperties;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import com.wlj.form.User;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.UnsupportedEncodingException;

@RestController
@RequestMapping("/user")
public class UserController {


//    @Autowired
//    private ProviderSignInUtils providerSignInUtils;

//    @Autowired
//    private AppSignUpUtils appSignUpUtils;

    @Autowired
    private WljSecurityProperties securityProperties;
    /**
     * 基于session，适用浏览器环境
     * @param user
     * @param request
     */
//    @PostMapping("/regist")
//    public void regist(User user, HttpServletRequest request){
        //无论注册还是绑定都会拿到一个用户标识
//        String userId = user.getUsername();

        //当社交登录时业务用户不存在则跳转到注册页
        // 添加userConnection用户社交账号对应数据，若是因为社交登录的关系调用的该注册接口，则下面语句会生效
        //但是该providerSignInUtils是基于session的
//        providerSignInUtils.doPostSignUp(userId,new ServletWebRequest(request));
//    }



    /**
     * 基于redis获取social用户信息，适用app环境
     */
//    @PostMapping("/regist")
//    public void regist(User user, HttpServletRequest request){
//        //无论注册还是绑定都会拿到一个用户标识
//        String userId = user.getUsername();
//        appSignUpUtils.doPostSignUp(new ServletWebRequest(request),userId);
//    }




    @GetMapping("/{id:\\d+}")
    @JsonView(User.UserDetailView.class)
    public User getInfo(@PathVariable String id){
        User user = new User();
        user.setUsername("com/wlj");
        //测试统一异常处理
//        throw new CustomException("303","哈哈");
        return user;
    }



    //当使用jwt作为token时，要修改一下
//    @GetMapping("/me")
//    public Object getCurrentUser3(@AuthenticationPrincipal UserDetails user){
//        return user;
//    }

    //使用jwt作为token
    @GetMapping("/me")
    public Object getCurrentUser3(Authentication user,HttpServletRequest request) throws UnsupportedEncodingException {
        String header = request.getHeader("Authorization");
        String jwtToken = StringUtils.substringAfter(header, "bearer ");
        Claims body = Jwts.parser().setSigningKey(securityProperties.getOauth2().getJwtSigningKey().getBytes("UTF-8"))
                .parseClaimsJws(jwtToken).getBody();
        String company = (String) body.get("company");
        System.out.println("增强信息company:"+company);
        return user;
    }



    //参数校验的错误信息将放到errors里
    //添加参数BindingResult，将进入方法体!，否则不进，请求直接被框架打回
//    @PostMapping
//    public User create(@Valid @RequestBody User user, BindingResult errors){
//        if(errors.hasErrors()){
//            errors.getAllErrors().stream().forEach(error-> {
//                FieldError fieldError = (FieldError) error;
//                String message=fieldError.getField()+": "+error.getDefaultMessage();
//                System.out.println(error.getDefaultMessage());
//            });
//        }
//        user.setId("1");
//        return user;
//    }

    //参数校验的错误直接被框架打回
    @PostMapping
    public User create(@Valid @RequestBody User user){
        user.setId("1");
        return user;
    }

}
